import { Button, Checkbox, Container, Group, Pagination, Table, Modal, Text, TextInput, NumberInput } from "@mantine/core";
import { useEffect, useState } from "react";
import axios from "axios";
import { notifications } from '@mantine/notifications';
import { modals } from '@mantine/modals';

interface Phone {
    id: number;
    phone_name: string;
    phone_brand: string;
    phone_price: number;
    ram_size: string;
    rom_size: number;
    screen_size: number;
    screen_resolution: string;
    cpu_xinghao: string;
}

function PhonePage() {
    const [selectedRows, setSelectedRows] = useState<number[]>([]);
    const [phoneList, setPhoneList] = useState<Phone[]>([]);
    const [pageInfo, setPageInfo] = useState<any>();
    const [detailsModalOpen, setDetailsModalOpen] = useState(false);
    const [currentPhone, setCurrentPhone] = useState<any>(null);
    const [editModalOpen, setEditModalOpen] = useState(false);
    const [editingPhone, setEditingPhone] = useState<any>(null);

    useEffect(() => {
        getPhoneInfo({ page: 1, per_page: 10 })
    }, [])

    const getPhoneInfo = (condition: any) => {
        axios.get("/app-api/get-phones", { params: condition }).then((res) => {
            setPhoneList(res.data.phones)
            setPageInfo(res.data.pagination)
        })
    }

    const handleViewDetails = (phone: any) => {
        setCurrentPhone(phone);
        setDetailsModalOpen(true);
    };

    const handleEdit = (phone: any) => {
        setEditingPhone({
            id: phone.id,
            phone_name: phone.phone_name,
            phone_brand: phone.phone_brand,
            phone_price: phone.phone_price,
            ram_size: phone.ram_size,
            rom_size: phone.rom_size,
            screen_size: phone.screen_size,
            screen_resolution: phone.screen_resolution,
            cpu_xinghao: phone.cpu_xinghao
        });
        setEditModalOpen(true);
    };

    const handleSaveEdit = () => {
        axios.put(`/app-api/update-phone/${editingPhone.id}`, editingPhone)
            .then(() => {
                setPhoneList(phoneList.map((phone: any) =>
                    phone.id === editingPhone.id ? editingPhone : phone
                ));
                setEditModalOpen(false);
                notifications.show({
                    title: '修改成功',
                    message: '记录已成功更新',
                    color: 'green',
                });
            })
            .catch((error) => {
                notifications.show({
                    title: '修改失败',
                    message: '更新记录时发生错误',
                    color: 'red',
                });
            });
    };

    const handleDelete = (phoneId: number) => {
        modals.openConfirmModal({
            title: '确认删除',
            centered: true,
            children: (
                <Text size="sm">
                    您确定要删除这条记录吗？此操作不可撤销。
                </Text>
            ),
            labels: { confirm: '确认删除', cancel: '取消' },
            confirmProps: { color: 'red' },
            cancelProps: { color: 'gray' },
            onConfirm: () => {
                axios.delete(`/app-api/delete-phone/${phoneId}`).then(() => {
                    setPhoneList(phoneList.filter((phone: any) => phone.id !== phoneId));
                    notifications.show({
                        title: '删除成功',
                        message: '记录已成功删除',
                        color: 'green',
                    });
                });
            },
        });
    };

    const rows = phoneList.map((element: any) => (
        <Table.Tr
            key={element.id}
            bg={selectedRows.includes(element.id) ? 'var(--mantine-color-blue-light)' : undefined}
        >
            <Table.Td>{element.phone_name}</Table.Td>
            <Table.Td>{element.phone_brand}</Table.Td>
            <Table.Td>{element.phone_price}</Table.Td>
            <Table.Td>{element.ram_size}</Table.Td>
            <Table.Td>{element.rom_size}G</Table.Td>
            <Table.Td>{element.screen_size}"</Table.Td>
            <Table.Td>{element.screen_resolution}</Table.Td>
            <Table.Td>{element.cpu_xinghao}</Table.Td>
            <Table.Td>
                <Group gap={4} className="w-full flex justify-center items-center">
                    <Button size={'xs'} color={'green'} onClick={() => handleViewDetails(element)}>详情</Button>
                    {(localStorage.getItem('user_role') as string) == '0' && (
                        <>
                            <Button size={'xs'} onClick={() => handleEdit(element)}>编辑</Button>
                            <Button size={'xs'} color={'red'} onClick={() => handleDelete(element.id)}>删除</Button>
                        </>
                    )}
                </Group>
            </Table.Td>
        </Table.Tr>
    ));

    return (
        <div className={'mx-[unset]'}>
            <div></div>
            <div className={'py-[10px]'}>
                <Table.ScrollContainer minWidth={500}>
                </Table.ScrollContainer>
                <Table withTableBorder withColumnBorders stickyHeader>
                    <Table.Thead>
                        <Table.Tr>
                            <Table.Th align={'center'} className={"w-[200px]"}>
                                <div className={'w-full flex justify-center'}>名称</div>
                            </Table.Th>
                            <Table.Th align={'center'} className={'align-middle'}>品牌</Table.Th>
                            <Table.Th>价格</Table.Th>
                            <Table.Th className={"w-[100px]"}>内存</Table.Th>
                            <Table.Th>存储</Table.Th>
                            <Table.Th>屏幕尺寸</Table.Th>
                            <Table.Th className={"w-[100px]"}>分辨率</Table.Th>
                            <Table.Th>处理器</Table.Th>
                            <Table.Th className={"w-[200px]"}>
                                <div className="w-full flex justify-center items-center">
                                    操作
                                </div>
                            </Table.Th>
                        </Table.Tr>
                    </Table.Thead>
                    <Table.Tbody>{rows}</Table.Tbody>
                </Table>
            </div>
            <div className={'py-[10px]'}>
                {
                    pageInfo && (
                        <Pagination total={pageInfo.pages as any} onPreviousPage={() => {
                            if (pageInfo.has_prev) {
                                getPhoneInfo({ page: pageInfo.prev_num, per_page: pageInfo.per_page })
                            }
                        }} onNextPage={() => {
                            if (pageInfo.has_next) {
                                getPhoneInfo({ page: pageInfo.next_num, per_page: pageInfo.per_page })
                            }
                        }} onChange={(page: number) => {
                            getPhoneInfo({ page: page, per_page: pageInfo.per_page })
                        }} />
                    )
                }
            </div>
            <Modal
                opened={editModalOpen}
                onClose={() => setEditModalOpen(false)}
                title="修改手机信息"
                size="lg"
            >
                {editingPhone && (
                    <div className="space-y-4">
                        <TextInput
                            label="名称"
                            value={editingPhone.phone_name}
                            onChange={(e) => setEditingPhone({
                                ...editingPhone,
                                phone_name: e.target.value
                            })}
                        />
                        <TextInput
                            label="品牌"
                            value={editingPhone.phone_brand}
                            onChange={(e) => setEditingPhone({
                                ...editingPhone,
                                phone_brand: e.target.value
                            })}
                        />
                        <NumberInput
                            label="价格"
                            value={editingPhone.phone_price}
                            onChange={(value) => setEditingPhone({
                                ...editingPhone,
                                phone_price: value
                            })}
                            decimalScale={2}
                            min={0}
                        />
                        <TextInput
                            label="内存"
                            value={editingPhone.ram_size}
                            onChange={(e) => setEditingPhone({
                                ...editingPhone,
                                ram_size: e.target.value
                            })}
                        />
                        <NumberInput
                            label="存储容量(G)"
                            value={editingPhone.rom_size}
                            onChange={(value) => setEditingPhone({
                                ...editingPhone,
                                rom_size: value
                            })}
                            min={0}
                        />
                        <NumberInput
                            label="屏幕尺寸(英寸)"
                            value={editingPhone.screen_size}
                            onChange={(value) => setEditingPhone({
                                ...editingPhone,
                                screen_size: value
                            })}
                            decimalScale={1}
                            min={0}
                        />
                        <TextInput
                            label="分辨率"
                            value={editingPhone.screen_resolution}
                            onChange={(e) => setEditingPhone({
                                ...editingPhone,
                                screen_resolution: e.target.value
                            })}
                        />
                        <TextInput
                            label="处理器"
                            value={editingPhone.cpu_xinghao}
                            onChange={(e) => setEditingPhone({
                                ...editingPhone,
                                cpu_xinghao: e.target.value
                            })}
                        />
                        <Group justify="flex-end" mt="md">
                            <Button variant="light" onClick={() => setEditModalOpen(false)}>取消</Button>
                            <Button onClick={handleSaveEdit}>保存</Button>
                        </Group>
                    </div>
                )}
            </Modal>
            <Modal opened={detailsModalOpen} onClose={() => setDetailsModalOpen(false)} title="手机详细信息" size="lg">
                {currentPhone && (
                    <div className="space-y-2">
                        <Text>基本信息</Text>
                        <div className="grid grid-cols-2 gap-4">
                            <Text>名称: {currentPhone.phone_name}</Text>
                            <Text>品牌: {currentPhone.phone_brand}</Text>
                            <Text>价格: {currentPhone.phone_price}</Text>
                            <Text>发布日期: {currentPhone.release_date}</Text>
                        </div>

                        <Text>处理器信息</Text>
                        <div className="grid grid-cols-2 gap-4">
                            <Text>型号: {currentPhone.cpu_xinghao}</Text>
                            <Text>频率: {currentPhone.cpu_frequency}</Text>
                            <Text>核心数: {currentPhone.cpu_cores}</Text>
                            <Text>GPU型号: {currentPhone.gpu_model}</Text>
                        </div>

                        <Text>内存与存储</Text>
                        <div className="grid grid-cols-2 gap-4">
                            <Text>RAM大小: {currentPhone.ram_size}</Text>
                            <Text>RAM类型: {currentPhone.ram_type}</Text>
                            <Text>ROM大小: {currentPhone.rom_size}G</Text>
                            <Text>ROM类型: {currentPhone.rom_type}</Text>
                        </div>

                        <Text>系统信息</Text>
                        <div className="grid grid-cols-2 gap-4">
                            <Text>系统版本: {currentPhone.os_version}</Text>
                            <Text>内核版本: {currentPhone.os_kernel}</Text>
                            <Text>其他硬件: {currentPhone.other_hardware}</Text>
                        </div>

                        <Text>屏幕参数</Text>
                        <div className="grid grid-cols-2 gap-4">
                            <Text>尺寸: {currentPhone.screen_size}"</Text>
                            <Text>分辨率: {currentPhone.screen_resolution}</Text>
                            <Text>刷新率: {currentPhone.refresh_rate}</Text>
                            <Text>像素密度: {currentPhone.pixel_density}</Text>
                            <Text>色彩: {currentPhone.screen_color}</Text>
                            <Text>亮度: {currentPhone.screen_brightness}</Text>
                            <Text>屏幕技术: {currentPhone.screen_tech}</Text>
                        </div>

                        <Text>网络与连接</Text>
                        <div className="grid grid-cols-2 gap-4">
                            <Text>网络频段: {currentPhone.network_bands}</Text>
                            <Text>WLAN: {currentPhone.wlan}</Text>
                            <Text>SIM卡类型: {currentPhone.sim_type}</Text>
                            <Text>蓝牙: {currentPhone.bluetooth}</Text>
                        </div>

                        <Text>摄像头参数</Text>
                        <div className="grid grid-cols-2 gap-4">
                            <Text>后置摄像头数量: {currentPhone.rear_cam_count}</Text>
                            <Text>前置摄像头数量: {currentPhone.front_cam_count}</Text>
                            <Text>后置摄像头像素: {currentPhone.rear_cam_pixels}</Text>
                            <Text>前置摄像头像素: {currentPhone.front_cam_pixels}</Text>
                            <Text>光圈: {currentPhone.aperture}</Text>
                        </div>

                        <Text>电池参数</Text>
                        <div className="grid grid-cols-2 gap-4">
                            <Text>电池类型: {currentPhone.battery_type}</Text>
                            <Text>快充: {currentPhone.fast_charge}</Text>
                        </div>

                        <Text>外观参数</Text>
                        <div className="grid grid-cols-2 gap-4">
                            <Text>厚度: {currentPhone.thickness}mm</Text>
                            <Text>宽度: {currentPhone.width}mm</Text>
                            <Text>长度: {currentPhone.length}mm</Text>
                            <Text>颜色: {currentPhone.colors}</Text>
                        </div>

                        <Text>其他参数</Text>
                        <div className="grid grid-cols-2 gap-4">
                            <Text>传感器: {currentPhone.sensors}</Text>
                            <Text>游戏功能: {currentPhone.gaming_features}</Text>
                            <Text>包装内容: {currentPhone.package_contents}</Text>
                        </div>
                    </div>
                )}
            </Modal>
        </div>
    )
}

const PhoneChatTable = (props: { phones: any[] }) => {
    const { phones } = props;
    const [detailsModalOpen, setDetailsModalOpen] = useState(false);
    const [currentPhone, setCurrentPhone] = useState<any>(null);
    const handleDetailsClick = (phone: any) => {
        setCurrentPhone(phone);
        setDetailsModalOpen(true);
    };
    return (
        <>
            <Modal opened={detailsModalOpen} onClose={() => setDetailsModalOpen(false)} title="手机详细信息" size="lg">
                {currentPhone && (
                    <div className="space-y-2">
                        <Text>基本信息</Text>
                        <div className="grid grid-cols-2 gap-4">
                            <Text>名称: {currentPhone.phone_name}</Text>
                            <Text>品牌: {currentPhone.phone_brand}</Text>
                            <Text>价格: {currentPhone.phone_price}</Text>
                            <Text>发布日期: {currentPhone.release_date}</Text>
                        </div>

                        <Text>处理器信息</Text>
                        <div className="grid grid-cols-2 gap-4">
                            <Text>型号: {currentPhone.cpu_xinghao}</Text>
                            <Text>频率: {currentPhone.cpu_frequency}</Text>
                            <Text>核心数: {currentPhone.cpu_cores}</Text>
                            <Text>GPU型号: {currentPhone.gpu_model}</Text>
                        </div>

                        <Text>内存与存储</Text>
                        <div className="grid grid-cols-2 gap-4">
                            <Text>RAM大小: {currentPhone.ram_size}</Text>
                            <Text>RAM类型: {currentPhone.ram_type}</Text>
                            <Text>ROM大小: {currentPhone.rom_size}G</Text>
                            <Text>ROM类型: {currentPhone.rom_type}</Text>
                        </div>

                        <Text>系统信息</Text>
                        <div className="grid grid-cols-2 gap-4">
                            <Text>系统版本: {currentPhone.os_version}</Text>
                            <Text>内核版本: {currentPhone.os_kernel}</Text>
                            <Text>其他硬件: {currentPhone.other_hardware}</Text>
                        </div>

                        <Text>屏幕参数</Text>
                        <div className="grid grid-cols-2 gap-4">
                            <Text>尺寸: {currentPhone.screen_size}"</Text>
                            <Text>分辨率: {currentPhone.screen_resolution}</Text>
                            <Text>刷新率: {currentPhone.refresh_rate}</Text>
                            <Text>像素密度: {currentPhone.pixel_density}</Text>
                            <Text>色彩: {currentPhone.screen_color}</Text>
                            <Text>亮度: {currentPhone.screen_brightness}</Text>
                            <Text>屏幕技术: {currentPhone.screen_tech}</Text>
                        </div>

                        <Text>网络与连接</Text>
                        <div className="grid grid-cols-2 gap-4">
                            <Text>网络频段: {currentPhone.network_bands}</Text>
                            <Text>WLAN: {currentPhone.wlan}</Text>
                            <Text>SIM卡类型: {currentPhone.sim_type}</Text>
                            <Text>蓝牙: {currentPhone.bluetooth}</Text>
                        </div>

                        <Text>摄像头参数</Text>
                        <div className="grid grid-cols-2 gap-4">
                            <Text>后置摄像头数量: {currentPhone.rear_cam_count}</Text>
                            <Text>前置摄像头数量: {currentPhone.front_cam_count}</Text>
                            <Text>后置摄像头像素: {currentPhone.rear_cam_pixels}</Text>
                            <Text>前置摄像头像素: {currentPhone.front_cam_pixels}</Text>
                            <Text>光圈: {currentPhone.aperture}</Text>
                        </div>

                        <Text>电池参数</Text>
                        <div className="grid grid-cols-2 gap-4">
                            <Text>电池类型: {currentPhone.battery_type}</Text>
                            <Text>快充: {currentPhone.fast_charge}</Text>
                        </div>

                        <Text>外观参数</Text>
                        <div className="grid grid-cols-2 gap-4">
                            <Text>厚度: {currentPhone.thickness}mm</Text>
                            <Text>宽度: {currentPhone.width}mm</Text>
                            <Text>长度: {currentPhone.length}mm</Text>
                            <Text>颜色: {currentPhone.colors}</Text>
                        </div>

                        <Text>其他参数</Text>
                        <div className="grid grid-cols-2 gap-4">
                            <Text>传感器: {currentPhone.sensors}</Text>
                            <Text>游戏功能: {currentPhone.gaming_features}</Text>
                            <Text>包装内容: {currentPhone.package_contents}</Text>
                        </div>
                    </div>
                )}
            </Modal>
            <Table verticalSpacing="xs" highlightOnHover striped withColumnBorders
                styles={{
                    thead: {
                        '& tr': {
                            backgroundColor: '#007bff',
                            color: 'white'
                        },
                        '& th': {
                            borderBottom: '2px solid #e0e0e0'
                        }
                    },
                    tbody: {
                        '& tr': {
                            '&:nth-of-type(even)': {
                                backgroundColor: '#f8f9fa'
                            },
                            '&:hover': {
                                backgroundColor: '#e9ecef'
                            }
                        }
                    },
                    td: {
                        border: '1px solid #f0f0f0'
                    }
                }}>
                <Table.Thead>
                    <Table.Tr>
                        <Table.Th>名称</Table.Th>
                        <Table.Th>品牌</Table.Th>
                        <Table.Th>价格</Table.Th>
                        <Table.Th>发布日期</Table.Th>
                        <Table.Th>操作</Table.Th>
                    </Table.Tr>
                </Table.Thead>
                <Table.Tbody>
                    {phones.map((phone: any, index: any) => {
                        return (
                            <Table.Tr key={index}>
                                <Table.Td>{phone.phone_name}</Table.Td>
                                <Table.Td>{phone.phone_brand}</Table.Td>
                                <Table.Td>{phone.phone_price}￥</Table.Td>
                                <Table.Td>{phone.release_date}</Table.Td>
                                <Table.Td>
                                    <Group>
                                        <Button onClick={() => handleDetailsClick(phone)}>详情</Button>
                                        <Button color="green" onClick={() => { window.open(phone.url, '_blank') }}>网站</Button>
                                    </Group>
                                </Table.Td>
                            </Table.Tr>
                        )
                    })}
                </Table.Tbody>
            </Table>
        </>
    )
}

export { PhoneChatTable, PhonePage }